from collections import defaultdict, Counter
import random

def build_ngram_model(text, n=2):
    model = defaultdict(Counter)
    for i in range(len(text) - n):
        context, word = tuple(text[i:i+n-1]), text[i+n-1]
        model[context][word] += 1
    return model

def generate_with_ngram(model, max_len=20):
    context = random.choice(list(model.keys()))
    output = list(context)
    for i in range(max_len):
        if context not in model:
            break
        next_word = random.choices(list(model[context].keys()), weights=model[context].values())[0]
        output.append(next_word)
        context = tuple(output[-len(context):])
    return ' '.join(output)

text = "我 爱 学习 人工 智能".split()
model = build_ngram_model(text, n=2)
generated_text = generate_with_ngram(model)
print(generated_text)
